package com.atao.baokede.utils;


import com.atao.baokede.enums.TokenType;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "atao";

    //接收业务数据,生成token并返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365))
                .sign(Algorithm.HMAC256(KEY));
    }

    //接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }


    // 根据token判断是用户还是商户
    public static TokenType getTokenType(String token) {
        try {
            Map<String, Object> claims = parseToken(token);
            if (claims.containsKey("type")) {
                String type = (String) claims.get("type");
                if ("user".equals(type)) {
                    return TokenType.USER;
                } else if ("merchant".equals(type)) {
                    return TokenType.MERCHANT;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}